<template>
    <div class="avatar-upload">
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeUpload"
            :http-request="handleUpload" accept=".jpg,.jpeg,.png,.gif,.webp">
            <el-avatar v-if="avatarUrl" :size="size" :src="avatarUrl" class="avatar" />
            <div v-else class="avatar-placeholder" :style="{ width: size + 'px', height: size + 'px' }">
                <el-icon :size="size / 2">
                    <Plus />
                </el-icon>
                <div class="upload-text">上传头像</div>
            </div>

            <template #tip>
                <div class="el-upload__tip">
                    支持 jpg、png、gif、webp 格式，大小不超过 10MB
                </div>
            </template>
        </el-upload>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const props = defineProps({
    size: {
        type: Number,
        default: 100
    },
    avatarUrl: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['update:avatarUrl', 'upload-success'])

const userStore = useUserStore()
const uploading = ref(false)

const beforeUpload = (file) => {
    const isImage = /\.(jpg|jpeg|png|gif|webp)$/i.test(file.name)
    const isLt10M = file.size / 1024 / 1024 < 10

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt10M) {
        ElMessage.error('图片大小不能超过 10MB!')
        return false
    }
    return true
}

const handleUpload = async (options) => {
    const { file } = options
    uploading.value = true

    try {
        const response = await userStore.uploadUserAvatar(file)

        ElMessage.success(response.msg || '头像上传成功')
        emit('update:avatarUrl', response.data.avatar)
        emit('upload-success', response.data.avatar)
    } catch (error) {
        ElMessage.error(error.message || '头像上传失败')
    } finally {
        uploading.value = false
    }
}
</script>

<style scoped>
.avatar-uploader {
    display: inline-block;
    text-align: center;
}

.avatar-uploader :deep(.el-upload) {
    border: 2px dashed #d9d9d9;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
}

.avatar-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #8c939d;
    background-color: #f5f7fa;
    border-radius: 50%;
}

.upload-text {
    font-size: 12px;
    margin-top: 4px;
}

.avatar {
    display: block;
}
</style>